<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/13
 * Time: 11:16
 */

namespace App\Rep;


use App\Exceptions\ApiException;
use App\Models\DispatchOrder;
use App\Models\Employee;
use App\Models\EmployeeJobType;
use App\Models\JobType;
use App\Models\Order;
use App\Models\OrderChild;
use App\Models\Product;
use App\Models\ProductJobType;
use App\Models\Rbac\User;
use App\Models\Rbac\UserRole;
use Illuminate\Support\Facades\DB;


class EmployeeRep
{
    /**
     * 获取员工列表
     * @param $params
     * @return mixed
     */
    public function getEmployeeListRep($params){
        $params['roles_id'] = 16;
        //$list = User::Search($params)->with(['employee','role'])->orderBy('id','desc')->paginate($params['per_page']??10);
        $list = Employee::Search($params)
            ->with(['user'=>function($q){
                $q->with(['role']);
            },'job_type'])
            ->orderBy('id','desc')->paginate($params['per_page']??10);
        return $list;
    }

    /**
     * 添加员工
     * @param $params
     * @return Employee|array
     */
    /**
     * 添加员工
     * @param $params
     * @return Employee|array
     */
    public function createEmployeeRep($params){
        DB::beginTransaction();
        try{
            $user = User::find($params['users_id']);
            if(isset($params['id']) && !empty($params['id'])){
                $model = Employee::find($params['id']);
            }else{

                $model = Employee::where('user_id',$params['users_id'])->first();
                if($model){
                    if($model->is_del == 2){
                        throw new ApiException(20001,'当前账号已绑定员工');
                    }
                }else{
                    $model = new Employee();
                }
            }
            $model->employee_name = $user->company_name;
            $model->user_id=$params['users_id'];
            $model->phone = $params['phones']??"";
            $model->address = $params['address']??'';
            $model->job_type_id = $params['job_type_id'];
            $model->id_card = $params['id_card']??'';
            $model->native_place = $params['native_place']??'';
            $model->emergency_contact = $params['emergency_contact']??'';
            $model->emergency_contact_phone = $params['emergency_contact_phone']??'';
            $model->card_number = $params['card_number']??null;
            $model->base_pay = $params['base_pay']??'';
            if(!empty($params['hiredate'])){
                $model->hiredate = $params['hiredate']??'';
            }
            $model->submit_way = $params['submit_way'];
            //$model->level = $params['level']??'';
            $model->is_del=2;
            $model->save();
            $data = User::with(['role','employee'])->find($model->user_id);
            DB::commit();
            return ['code'=>0,'data'=>$data,'msg'=>''];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }
    }

    /**
     * 删除员工
     * @param $params
     */
    public function delEmployeeRep($params){
        $model = Employee::where('id',$params['id'])->first();
        $model->is_del = $params['is_del'];
        $model->save();
        return $model;
    }

    /**
     * 根据type_job_id获取员工列表
     * @param $params
     */
    public function getEmployeeListByJobTypeIDRep($params){
        return Employee::where('is_del',2)->where('job_type_id',$params['job_type_id'])->get();
    }

    /**
     * 查询员工可领取订单
     * 1.指派的订单
     * 2.工种未领取的订单
     * 备注：排序按派单顺序设置
     * 工种可领几条数据就显示几条数据
     */
    public function searchPensionableOrderChildRep($params){
        //p(111);
        $employee_user_id = $params['user_id'];

        $employeeInfo = $this->setEmployeeInfo($params['user_id']);
        //p($employeeInfo);
        if($employeeInfo['unclaimed_num']<=0){
            return ['code'=>1017,'data'=>[],'msg'=>'没有可领取订单'];
        }

        $job_type_id = $this->getJobTypeIdByEmployeeUserId($employee_user_id);
        //p($job_type_id);
        $orderByArr = (new DispatchOrderRep())->getDispatchOrderSortRep();
        $list = OrderChild::where('order_child.is_del',2)->where('order.status',1)
            ->where(function($q)use($employee_user_id,$job_type_id){
                $q->orwhere(function($q)use($employee_user_id){
                    //指派
                    $q->where('order_child.status',3)
                        ->where('order_child.employee_user_id',$employee_user_id)
                        ->where('order_child.is_appoint',1);
                })->orwhere(function($q)use($job_type_id){
                    $q->where('order_child.job_type_id',$job_type_id)
                        ->where('order_child.is_epiboly',2)//是否外包
                        ->where('order_child.is_appoint',2)//是否指派
                        ->where('order_child.status',3);
                });
                $q->whereNull('order_child.submit_time');
                //->whereNull('order_child.draw_time');//领取时间
            })->with(['job_type','employee','order'=>function($q){
                return $q->with(['color'=>function($q){
                    return $q->select('id','color');
                },'product'=>function($q){
                    return $q->select('id','product_name');
                },'customer'=>function($q){
                    return $q->select('id','customer_name','customer_address');
                },'modelNumber'=>function($q){
                    return $q->select('id','model_number');
                },'specification'=>function($q){
                    return $q->select('id','specification');
                },'finish_product'=>function($q){
                    return $q->select('order_id','num','warehouse_id','goods_shelf_id');
                }]);
            }]) ->join('order', 'order.id', '=', 'order_child.order_id')
            ->select(
                'order_child.*',
                'order.id as orders_id',
                'order.color_id',
                'order.customer_id',
                'order.model_number_id',
                'order.product_id',
                'order.status')
            ->orderBy($orderByArr[0]['field_name'],$orderByArr[0]['sortord'])
            ->orderBy($orderByArr[1]['field_name'],$orderByArr[1]['sortord'])
            ->orderBy($orderByArr[2]['field_name'],$orderByArr[2]['sortord'])
            ->orderBy($orderByArr[3]['field_name'],$orderByArr[3]['sortord'])
            //->skip(0)->take($employeeInfo['unclaimed_num'])
            //->offset(0)
            //->limit($employeeInfo['unclaimed_num'])
            ->get();
        //p($list->toArray());

        foreach($list as $k=>$v){

            $jobTypeRep = new JobTypeRep();
            $is_restrict = $jobTypeRep->judgeIsRestrict($v->job_type_id,$v->product_id);
            //p($is_restrict);
            //是否限制流程
            if($is_restrict){
                //限制流程，判断上个工序是否完成
                $res = $this->judgeLastProcess($v->order_id,$v->job_type_id,$v->product_id);
                //p($res);
                if(!$res){
                    //return ['code'=>1018,'data'=>[],'msg'=>'限制流程，有尚未完成的工序'];
                    unset($list[$k]);
                }
            }

        }
        $list = array_merge($list->toArray());
        //p($list);
        $list = array_splice($list,0,$employeeInfo['unclaimed_num']);


        return $list;
    }

    /**
     * 获取员工的工种id
     * @param $employee_user_id
     * @return $job_type_id
     */
    public function getJobTypeIdByEmployeeUserId($employee_user_id){
        $employee = Employee::where('user_id',$employee_user_id)->first();
        return $employee->job_type_id;
    }

    /**
     * 员工领取订单
     * @param $params
     * user_id
     * order_child_id
     */
    public function drawOrderChildRep($params){
        $employeeInfo = $this->setEmployeeInfo($params['user_id']);
        if($employeeInfo['unclaimed_num']<=0){
            return ['code'=>1017,'data'=>$employeeInfo,'msg'=>'不可领取多个工单'];
        }
        $order_child = OrderChild::where('id',$params['order_child_id'])->with(['order'=>function($q){
            return $q->with(['customer','modelNumber','color','specification']);
        },'employee','job_type'])->first();
        if(!empty($order_child['draw_time'])){
            return ['code'=>1023,'data'=>$employeeInfo,'msg'=>'该工单已领取，无需再次领取'];
        }
        $jobTypeRep = new JobTypeRep();
        $is_restrict = $jobTypeRep->judgeIsRestrict($order_child->job_type_id,$order_child->order->product_id);
        if($is_restrict){
            //限制流程，判断上个工序是否完成
            $res = $this->judgeLastProcess($order_child->order_id,$order_child->job_type_id,$order_child->order->product_id);
            if(!$res){
                return ['code'=>1018,'data'=>[],'msg'=>'限制流程，有尚未完成的工序'];
            }
        }
        $order_child->employee_user_id = $params['user_id'];
        $order_child->draw_time = date("Y-m-d H:i:s",time());
        $order_child->operator_user_id = $params['user_id'];
        $order_child->status = 2;
        $order_child->save();
        $order_child = OrderChild::where('id',$params['order_child_id'])->with(['order'=>function($q){
            return $q->with(['customer','modelNumber','color','specification']);
        },'employee','job_type'])->first();
        return ['code'=>0,'data'=>$order_child,'msg'=>'success'];
    }

    /**
     * 提交订单
     */
    public function submitOrderChildRep($params){
        $order_child = OrderChild::where('id',$params['order_child_id'])->first();
        if(!empty($order_child->submit_time) && $order_child->status = 1){
            return ['code'=>1022,'data'=>[],'msg'=>'该工单已提交，无需再次提交'];
        }
        $order_child->submit_time = date("Y-m-d H:i:s",time());
        $order_child->status = 1;
        if(!empty($params['image1']??'')){
            $order_child->image1 = $params['image1'];
        }
        if(!empty($params['image2']??'')){
            $order_child->image2 = $params['image2'];
        }
        if(!empty($params['image3']??'')){
            $order_child->image3 = $params['image3'];
        }
        if(!empty($params['image4']??'')){
            $order_child->image4 = $params['image4'];
        }
        $order_child->save();
        $orderRep = new OrderRep();
        $orderRep->selectOrderChildStatus($order_child->order_id);
        return ['code'=>0,'data'=>$order_child,'msg'=>'success'];
    }

    /**
     * 打印 提交订单
     */
    public function submitOrderChildByDayinRep($params){
        $order = Order::where('order_number',$params['order_number'])->first();
        if(!$order){
            return ['code'=>2003,'data'=>[],'msg'=>'订单号错误！'];
        }
        $order_child = OrderChild::where('order_id',$order->id)->where('employee_user_id',$params['employee_user_id'])->first();

        if(!empty($order_child->submit_time) && $order_child->status = 1){
            return ['code'=>1022,'data'=>[],'msg'=>'该工单已提交，无需再次提交'];
        }
        $order_child->submit_time = date("Y-m-d H:i:s",time());
        $order_child->status = 1;
        if(!empty($params['image1']??'')){
            $order_child->image1 = $params['image1'];
        }
        if(!empty($params['image2']??'')){
            $order_child->image2 = $params['image2'];
        }
        if(!empty($params['image3']??'')){
            $order_child->image3 = $params['image3'];
        }
        if(!empty($params['image4']??'')){
            $order_child->image4 = $params['image4'];
        }
        $order_child->save();
        $orderRep = new OrderRep();
        $orderRep->selectOrderChildStatus($order_child->order_id);
        return ['code'=>0,'data'=>$order_child,'msg'=>'success'];
    }





    /**
     * 查询【已完成/未完成】的订单
     * @param $params
     */
    public function searchCompletedOrUnfinishedOrderChildRep($params){
        $status = $params['status']??1;
        $model = OrderChild::where('employee_user_id',$params['user_id'])
            ->where(function($q)use($params){
                if($params['status'] == 1){
                    $field = 'submit_time';
                }elseif($params['status'] == 2){
                    $field = 'draw_time';
                }
                if(!empty($params['start_time']) && !empty($params['end_time'])){
                    $start_time = $params['start_time']." 00:00:00";
                    $end_time = $params['end_time']." 23:59:59";
                    $q->whereBetween($field,[$start_time,$end_time]);
                }
            })
            ->where('is_del','<>','1')
            ->with(['order'=>function($q){
            return $q->with(['customer','modelNumber','color','specification']);
        },'employee','job_type']);
        if($status == 1){
            $list = $model
                ->where('status',$status)
                ->whereNotNull('submit_time')
                ->paginate($params['per_page']??10);
        }elseif($status == 2){
            $list = $model->where('status',$status)->whereNull('submit_time')
                ->paginate($params['per_page']??10);
        }
        foreach($list as $k=>$v){
            $list[$k]->price = $v->price * $v->order->num;
        }
        return $list;
    }

    /**
     * 判断上一个工序是否完成
     */
    public function judgeLastProcess($order_id,$job_type_id,$product_id){
        $product_job_type = ProductJobType::where('job_type_id',$job_type_id)->where('product_id',$product_id)->first();
        //$sort = $product_job_type->sort;
        $pid = $product_job_type->pid;
        //p($pid);
        if($pid != 0){
            $pid_arr = explode(',',$pid);
            //p($pid_arr);
            foreach($pid_arr as $k=>$v){
                $status = OrderChild::where('order_id',$order_id)
                    ->where('is_del',2)
                    ->where('job_type_id',$v)
                    ->value('status');
                //p($status);
                //echo $status;
                if($status != 1){
                    return false;
                    break;
                }
            }
        }

        return true;
    }

    /**
     * 设置员工登录，员工基本信息
     * @param $user_id
     */
    public function setEmployeeInfo($user_id){
        $info = User::where('id',$user_id)->first();
        $employee = Employee::where('user_id',$user_id)->with('job_type')->first();
        //p($employee);
        $job_type = $employee->job_type;
        //p($job_type);
        //可领单数
        $arr['multi_order_num'] = 1;
        if($job_type->is_multi == 1){
            $arr['multi_order_num'] = $job_type->multi_order_num;
        }
        //已领单数
        $arr['already_received_num'] = OrderChild::where('status',2)->where('employee_user_id',$user_id)->count();
        //未领取数
        $arr['unclaimed_num'] = $arr['multi_order_num'] - $arr['already_received_num'];
        return $arr;
    }





}
